package com.gexiaobao.pigeon.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.widget.ImageView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.flyjingfish.openimagelib.OpenImage
import com.flyjingfish.openimagelib.enums.MediaType
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.UIMessageEntity
import com.gexiaobao.pigeon.app.model.bean.ImContentResponse
import com.gexiaobao.pigeon.app.network.HttpUtil
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil.setColor
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityMainTestInputBinding
import com.gexiaobao.pigeon.ui.adapter.ChatMessageAdapter
import com.gexiaobao.pigeon.ui.adapter.EmotionsAdapter
import com.gexiaobao.pigeon.viewmodel.MallImModel
import com.google.gson.Gson
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.xinbida.wukongim.WKIM
import com.xinbida.wukongim.entity.WKChannelType
import com.xinbida.wukongim.entity.WKMsg
import com.xinbida.wukongim.interfaces.IGetSocketIpAndPortListener
import com.xinbida.wukongim.message.type.WKConnectStatus
import com.xinbida.wukongim.msgmodel.WKImageContent
import com.xinbida.wukongim.msgmodel.WKTextContent
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import com.zs.easy.imgcompress.util.GBMBKBUtil
import me.hgj.jetpackmvvm.ext.util.toJson
import me.hgj.jetpackmvvm.util.LogUtils
import org.json.JSONException
import org.json.JSONObject
import java.io.File


/**
 * @Author : hxw
 * @Date : 2024/2/28 17:16
 * @Describe : 客服聊天
 */
class TestInputActivity : BaseActivity<MallImModel, ActivityMainTestInputBinding>() {

    private val adapter: ChatMessageAdapter by lazy { ChatMessageAdapter() }
    private val emojAdapter: EmotionsAdapter by lazy { EmotionsAdapter(arrayListOf()) }
    private var channelID = ""
    private var mChannelType: Byte = 0
    private var mLoginUID = ""
    private var mUid = ""
    private var token = ""
    private var localPath = ""
    private val emojiChar =
        arrayOf(
            "😀", "😃", "😄", "😁", "😆", "😅", "🤣", "😂", "🙂", "🙃", "😉", "😊", "😇", "🥰", "😍", "🤩", "😘", "😗", "😚", "😙",
            "😋", "😛", "😜", "🤪", "😝", "🤑", "🤗", "🤭", "🤫", "🤔", "🤐", "🤨", "😐", "😑", "😶", "😏", "😒", "🙄", "😬", "🤥", "😶‍",
            "😮‍", "😌", "😔", "😪", "🤤", "😴", "😷", "🤒", "🤕", "🤢", "🤮", "🤧", "🥵", "🥶", "🥴", "😵", "🤯", "😵‍", "🤠", "🥳", "😎",
            "🤓", "🧐", "😕", "😟", "🙁", "☹", "😮", "😯", "😲", "😳", "🥺", "😦", "😧", "😨", "😰", "😥", "😢", "😭", "😱", "😖", "😣",
            "😞", "😓", "😩", "😫", "🥱", "😤", "😡", "😠", "🤬", "😈", "👿", "💀", "☠", "💩", "🤡", "🙈", "🙉", "🙊", "💋", "💔", "❤"
        )

    override fun initView(savedInstanceState: Bundle?) {
        setColor(this, ContextCompat.getColor(this, R.color.color_fe4542), 0)

        token = intent.getStringExtra("token").toString()
        mLoginUID = KvUtils.decodeString(Constant.USERID)
        WKIM.getInstance().init(this, mLoginUID, token)
        channelID = intent.getStringExtra("channelId").toString()
        mUid = intent.getStringExtra("uid").toString()
        mChannelType = WKChannelType.PERSONAL
        /** 初始化聊天内容的recyclerview */
        mDatabind.recycleView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mDatabind.recycleView.adapter = adapter

        if (intent.hasExtra("isService")) {
            val isService = intent.getBooleanExtra("isService", false)
            adapter.setIsService(isService)
        }

        /** 初始化表情符号的recyclerview */
        mDatabind.panelView.recyclerviewEmoticons.init(GridLayoutManager(this, 6), emojAdapter).addItemDecoration(
            SpaceItemDecoration(0, 0)
        )
        val list: ArrayList<String> = emojiChar.toList() as ArrayList<String>
        emojAdapter.setList(list)

        onListener()
        getHistoryMessages()
        setUnReadMsg()
    }

    override fun onResume() {
        super.onResume()
        /** 连接 */
        WKIM.getInstance().connectionManager.connection()
    }

    private fun setUnReadMsg() {
        Thread {
            HttpUtil.getInstance().setUnReadMsg(mUid, channelID, mChannelType.toInt(), 0)
        }.start()
    }

    /** 获取历史聊天记录 */
    private fun getHistoryMessages() {
        Thread {
            HttpUtil.getInstance().getHistoryMsg(mLoginUID, channelID, mChannelType) { list ->
                if (list != null && list.size > 0) {
                    runOnUiThread {
                        adapter.setList(list)
                        mDatabind.recycleView.scrollToPosition(adapter.data.size - 1)
                    }
                } else {
                    adapter.setList(ArrayList())
                }
            }
        }.start()
    }

    @SuppressLint("SetTextI18n")
    private fun onListener() {
        emojAdapter.setOnItemClickListener { _, _, position ->
            mDatabind.chatInputEt.setText(mDatabind.chatInputEt.text.toString() + emojAdapter.data[position])
            mDatabind.chatInputEt.setSelection(mDatabind.chatInputEt.length())
        }

        adapter.addChildClickViewIds(R.id.contentIv)
        adapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.contentIv -> {
                    openImage(position)
                    LogUtils.debugInfo(adapter.data[position].toJson())
                }
            }
        }

        adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                super.onItemRangeInserted(positionStart, itemCount)
                mDatabind.recycleView.scrollToPosition(adapter.data.size - 1)
            }
        })

        /** 连接状态监听 */
        WKIM.getInstance().connectionManager.addOnConnectionStatusListener("main_act") { code: Int, _: String? ->
            when (code) {
                WKConnectStatus.success -> {
                    mDatabind.connectionTv.setText(R.string.connect_success)
                    mDatabind.connectionTv.setTextColor(ContextCompat.getColor(this, R.color.white))
                    mDatabind.connectionIv.setBackgroundResource(R.drawable.success)
                }

                WKConnectStatus.fail -> {
                    mDatabind.connectionTv.setText(R.string.connect_fail)
                    mDatabind.connectionTv.setTextColor(ContextCompat.getColor(this, R.color.over_orange))
                    mDatabind.connectionIv.setBackgroundResource(R.drawable.error)
                }

                WKConnectStatus.connecting -> {
                    mDatabind.connectionTv.setText(R.string.connecting)
                    mDatabind.connectionTv.setTextColor(ContextCompat.getColor(this, R.color.white))
                    mDatabind.connectionIv.setBackgroundResource(R.drawable.conn)
                }

                WKConnectStatus.noNetwork -> {
                    mDatabind.connectionTv.setText(R.string.no_net)
                    mDatabind.connectionTv.setTextColor(ContextCompat.getColor(this, R.color.nonet))
                    mDatabind.connectionIv.setBackgroundResource(R.drawable.nonet)
                }

                WKConnectStatus.kicked -> {
                    mDatabind.connectionTv.setText(R.string.other_device_login)
                    mDatabind.connectionTv.setTextColor(ContextCompat.getColor(this, R.color.white))
                    mDatabind.connectionIv.setBackgroundResource(R.drawable.conn)
                }
            }
        }

        /** 新消息监听 */
        WKIM.getInstance().msgManager.addOnNewMsgListener("new_msg") { msgList: List<WKMsg?> ->
            for (msg in msgList) {
                adapter.addData(UIMessageEntity(msg!!, 0))
            }
        }

        /** 监听发送消息入库返回 */
        WKIM.getInstance().msgManager.addOnSendMsgCallback("insert_msg") { msg: WKMsg? ->
            adapter.addData(UIMessageEntity(msg!!, 1))
        }

        /** 发送消息回执 */
        WKIM.getInstance().msgManager.addOnSendMsgAckListener("ack_key") { msg: WKMsg ->
            var i = 0
            val size = adapter.data.size
            while (i < size) {
                if (adapter.data[i].msg.clientSeq == msg.clientSeq) {
                    adapter.data[i].msg.status = msg.status
                    adapter.notifyItemChanged(i)
                    break
                }
                i++
            }
        }

        /** 长连接地址获取 */
        WKIM.getInstance().connectionManager.addOnGetIpAndPortListener { andPortListener: IGetSocketIpAndPortListener ->
            Thread {
                HttpUtil.getInstance()["/route", { code: Int, data: String ->
                    if (code == 200) {
                        try {
                            val jsonObject = JSONObject(data)
                            val tcp_addr = jsonObject.optString("tcp_addr")
                            val strings = tcp_addr.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                            andPortListener.onGetSocketIpAndPort(strings[0], strings[1].toInt())
                        } catch (e: JSONException) {
                            throw RuntimeException(e)
                        }
                    }
                }]
            }.start()
        }

        mDatabind.ivChatBack.setOnClickListener {
            if (channelID != "null" && channelID.isNotEmpty()) {
                eventViewModel.toNotifyOutChat.value = channelID.toInt()
            }
            finish()
        }
        mDatabind.sendMsgTv.setOnClickListener {
            sendChatMsg()
        }
        mDatabind.sendImageBtn.setOnClickListener {
            selectSendPic()
        }
    }

    private fun openImage(position: Int) {
        val dataList: MutableList<String> = ArrayList()
        if (adapter.data.size != 0 && adapter.data.isNotEmpty()) {
            var url = ""
            for (data in adapter.data) {
                val result = data.msg.content
                val bean = Gson().fromJson(result, ImContentResponse::class.java)
                url = bean.url
                dataList.add(url)
            }
        }
        /** 在点击时调用（以下以RecyclerView为例介绍）
         * 点击ImageView所在的RecyclerView（也支持设置setClickViewPager2，
         * setClickViewPager，setClickGridView，setClickListView，
         * setClickImageView，setClickWebView，setNoneClickView）
         **/
        OpenImage.with(this)
            .setClickRecyclerView(
                mDatabind.recycleView
            ) { _, _ -> R.id.contentIv }
            /** 点击的ImageView的ScaleType类型（如果设置不对，打开的动画效果将是错误的） */
            .setSrcImageViewScaleType(ImageView.ScaleType.CENTER_CROP, true)
            .setImageUrlList(dataList, MediaType.IMAGE)
            .setClickPosition(position)
            .show()

    }

    override fun createObserver() {
        super.createObserver()
        /** 上传图片 */
        mViewModel.uploadImageResult.observe(this) {
            if (it != null) {
                val imageContent = WKImageContent()
                imageContent.height = 300
                imageContent.width = 200
                imageContent.url = it.address
                imageContent.localPath = localPath
                WKIM.getInstance().msgManager.sendMessage(imageContent, channelID, mChannelType)
            }
        }
    }

    private fun selectSendPic() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)//是否打开摄像按钮
            .isOpenClickSound(false)//图片选中的声音
            .isPreviewImage(false)//是否预览图片
            .isMaxSelectEnabledMask(false)
            .isDirectReturnSingle(true)//选择是否直接返回
            .setMaxSelectNum(1)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                if (!result.isNullOrEmpty()) {
                    localPath = result[0].path
                    // 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200）
                    EasyImgCompress.withSinglePic(this@TestInputActivity, result[0].realPath)
                        .maxPx(1200)
                        .maxSize(1024)
                        .enableLog(true)
                        .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                            override fun onStart() {
                                LogUtils.debugInfo("onStart")
                            }

                            override fun onSuccess(file: File) {
                                mViewModel.uploadFile(file)
                                LogUtils.debugInfo("onSuccess size = " + GBMBKBUtil.getSize(file.length()) + " getAbsolutePath= " + file.absolutePath)
                            }

                            override fun onError(error: String) {
                                LogUtils.debugInfo("onError error = $error")
                            }
                        }).start()
                }
            }

            override fun onCancel() {}
        })
    }

    private fun sendChatMsg() {
        val content = mDatabind.chatInputEt.text.toString()
        if (TextUtils.isEmpty(channelID)) {
            Toast.makeText(this, getString(R.string.input_channel_id), Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, getString(R.string.input_content), Toast.LENGTH_SHORT).show()
            return
        }

        WKIM.getInstance().msgManager.sendMessage(WKTextContent(content), channelID, mChannelType)
        mDatabind.chatInputEt.setText("")
    }

    override fun onStop() {
        super.onStop()
        WKIM.getInstance().connectionManager.disconnect(false)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 断开连接
        WKIM.getInstance().connectionManager.disconnect(true)
        // 取消监听
        WKIM.getInstance().msgManager.removeNewMsgListener("new_msg")
        WKIM.getInstance().msgManager.removeSendMsgCallBack("insert_msg")
        WKIM.getInstance().msgManager.removeSendMsgAckListener("ack_key")
        WKIM.getInstance().connectionManager.removeOnConnectionStatusListener("main_act")
    }

}
